/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.mybatis.generator.extend.servicegenerator;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.codegen.AbstractJavaClientGenerator;
import org.mybatis.generator.codegen.AbstractXmlGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.XMLMapperGenerator;
import org.mybatis.generator.config.PropertyRegistry;

import java.util.ArrayList;
import java.util.List;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;


/**
 * service实现层生成<br>
 * @author iron will
 */
public class JavaServiceGenerator extends AbstractJavaClientGenerator {

    public JavaServiceGenerator() {
        super(true);
    }

    public JavaServiceGenerator(boolean requiresMatchedXMLGenerator) {
        super(requiresMatchedXMLGenerator);
    }
    
    @Override
    public List<CompilationUnit> getCompilationUnits() {
    	progressCallback.startTask(getString("Progress.17", introspectedTable.getFullyQualifiedTable().toString()));
        CommentGenerator commentGenerator = context.getCommentGenerator();

        //FullyQualifiedJavaType parentType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaServiceType());
        TopLevelClass topLevelClass = new TopLevelClass(type);
     	/** 类加注解 */
        topLevelClass.addAnnotation("@Service");
        topLevelClass.addImportedType("org.springframework.stereotype.Service");
        topLevelClass.setVisibility(JavaVisibility.PUBLIC);
        commentGenerator.addJavaFileComment(topLevelClass);
        /** 类实现接口 */
        FullyQualifiedJavaType intf = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaInterfaceType());
        topLevelClass.addSuperInterface(intf);
        topLevelClass.addImportedType(intf);
        
        // 类加注释
        commentGenerator.addClassComment(topLevelClass, introspectedTable);

        String rootInterface = introspectedTable.getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
        if (!stringHasValue(rootInterface)) {
            rootInterface = context.getJavaClientGeneratorConfiguration().getProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
        }

        // 获取Mapper类
        FullyQualifiedJavaType mapper = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType());
        
        // 注入Mapper
        Field field = new Field();
        field.setVisibility(JavaVisibility.PRIVATE);
        field.setType(mapper);
        String shortName = mapper.getShortName();
        shortName = shortName.substring(0, 1).toLowerCase() + shortName.substring(1);
        field.setName(shortName);
        field.addAnnotation("@Autowired");
        
        topLevelClass.addImportedType("org.springframework.beans.factory.annotation.Autowired");
        topLevelClass.addField(field);
        topLevelClass.addImportedType(mapper);
        
        // 方法添加
        addSelectByPrimaryKeyMethod(topLevelClass);
        addInsertSelectiveMethod(topLevelClass);
        addUpdateByPrimaryKeySelectiveMethod(topLevelClass);
        addDeleteByPrimaryKeyMethod(topLevelClass);
        addSelectAllByEntitySelectiveMethod(topLevelClass);

        List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
        answer.add(topLevelClass);
        
        List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits();
        if (extraCompilationUnits != null) {
            answer.addAll(extraCompilationUnits);
        }

        return answer;
    }

    protected void addSelectByPrimaryKeyMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateSelectByPrimaryKey()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new SelectByPrimaryKeyMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }
    
    protected void addInsertSelectiveMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateInsertSelective()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new InsertMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }
    
    protected void addUpdateByPrimaryKeySelectiveMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateUpdateByPrimaryKeySelective()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new UpdateByPrimaryKeySelectiveMethodOfServiceGenerator();
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }
    
    protected void addDeleteByPrimaryKeyMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateDeleteByPrimaryKey()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new DeleteByPrimaryKeyMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }

    protected void addSelectAllByEntitySelectiveMethod(TopLevelClass topLevelClass) {
    	if (introspectedTable.getRules().generateSelectAllSelective()) {
    		AbstractJavaServiceMethodGenerator methodGenerator = new SelectAllByEntitySelectiveMethodOfServiceGenerator(false);
    		initializeAndExecuteGenerator(methodGenerator, topLevelClass);
    	}
    }
    
	protected void initializeAndExecuteGenerator(AbstractJavaServiceMethodGenerator methodGenerator,
			TopLevelClass topLevelClass) {
		methodGenerator.setContext(context);
		methodGenerator.setIntrospectedTable(introspectedTable);
		methodGenerator.setProgressCallback(progressCallback);
		methodGenerator.setWarnings(warnings);
		methodGenerator.addServiceElements(topLevelClass);
	}

    public List<CompilationUnit> getExtraCompilationUnits() {
        return null;
    }

    @Override
    public AbstractXmlGenerator getMatchedXMLGenerator() {
        return new XMLMapperGenerator();
    }
}
